//
//  FriendsTimelineController.m
//  TwitterFon
//
//  Created by kaz on 10/29/08.
//  Copyright 2008 naan studio. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "FriendsTimelineController.h"
#import "FriendsTimelineDataSource.h"
#import "ColorUtils.h"
#import "GuaziAppDelegate.h"
#import "UserTimelineController.h"
#import "FriendsTimelineTableView.h"

@interface FriendsTimelineController (Private)
- (void)scrollToFirstUnread;
- (void)didLeaveTab:(UINavigationController*)navigationController;
- (void) preparedForPicture;
@end


@implementation FriendsTimelineController


@synthesize tweetType;
@synthesize isLoaded;
@synthesize isRoot;
@synthesize timelineDataSource;

@synthesize grayBackgroundView;
@synthesize middlePicture;


#pragma mark - UIViewController methods

- (void) loadView
{
    self.tableView = [[[FriendsTimelineTableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
    
    /*
    if (!isLoaded) {
		//changed by zhaoqi
		self.timelineDataSource = [[[FriendsTimelineDataSource alloc] initWithController:self tweetType:tweetType] autorelease];
		self.tableView.dataSource = timelineDataSource;
		self.tableView.delegate   = timelineDataSource;
        [self loadTimeline];
    }*/
    
	UIBarButtonItem* refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh 
																				   target:self action:@selector(reload:)];
	self.navigationItem.rightBarButtonItem = refreshButton;
	[refreshButton release];
	
	UIBarButtonItem* postButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose 
                                                                                target:self action:@selector(post)];
	self.navigationItem.leftBarButtonItem = postButton;
	[postButton release];
    
    [self preparedForPicture];
}


- (void) viewDidUnload
{
    [super viewDidUnload];
    self.timelineDataSource = nil;
    self.middlePicture = nil;
    self.grayBackgroundView = nil;
}


- (void) dealloc
{
    [timelineDataSource release];
    [middlePicture release];
    [grayBackgroundView release];
    [super dealloc];
}


- (void)viewWillAppear:(BOOL)animated 
{
    if ( isRoot ) {
        UIView* view = self.navigationItem.titleView;
        if ( [view isKindOfClass:[UISegmentedControl class]] ) {
            UISegmentedControl* segment = (UISegmentedControl*) view;
            if ( tweetType == 0 ) {
                segment.selectedSegmentIndex = 0;
            }
            else if ( tweetType == 1 ) {
                segment.selectedSegmentIndex = 1;
            }
        }
    }
    
    User* user = [GuaziAppDelegate getAppDelegate].user;
    if ( [user.state compare:kUserStateValid] != NSOrderedSame ) {
        [super viewWillAppear:animated];
        [GuaziAppDelegate openRegisterView:self];
        return;
    }
    
    if ( isLoaded ) {
        [super viewWillAppear:animated];
        [self.tableView setContentOffset:contentOffset animated:false];
        [self.tableView reloadData];
    }
    else {
        [self restoreAndLoadTimeline:YES];
        [super viewWillAppear:animated];
    }
}


- (void)viewDidAppear:(BOOL)animated
{
    if (firstTimeToAppear) {
        firstTimeToAppear = false;
        [self scrollToFirstUnread];
    }
	[super viewDidAppear:animated];
    if (stopwatch) {
        LAP(stopwatch, @"viewDidAppear");
        [stopwatch release];
        stopwatch = nil;
    }
	
	//NSInteger selectedTab = [GuaziAppDelegate getAppDelegate].tabBarController.selectedIndex;
    //self.navigationController.navigationBar.tintColor = [UIColor navigationColorForTab:selectedTab];
    self.tableView.separatorColor = [UIColor lightGrayColor]; 
    self.navigationItem.title = @"好友动态";
}


- (void)viewWillDisappear:(BOOL)animated
{
    contentOffset = self.tableView.contentOffset;
}


- (void)viewDidDisappear:(BOOL)animated 
{
}


- (void)didReceiveMemoryWarning 
{
	NSLog(@"FriendsTimelineController didReceiveMemoryWarning");
}


#pragma mark - 加载数据

- (void)loadTimeline
{
    User* user = [GuaziAppDelegate getAppDelegate].user;
    NSString *username = user.name;
    NSString *password = user.password;
    if ([username length] != 0 && [password length] != 0) {
        self.navigationItem.leftBarButtonItem.enabled = false;
        [timelineDataSource getTimeline];
    }
    self.isLoaded = true;
}


- (void)restoreAndLoadTimeline:(BOOL)load
{
    firstTimeToAppear = true;
    stopwatch = [[Stopwatch alloc] init];
    
    self.timelineDataSource = [[[FriendsTimelineDataSource alloc] initWithController:self tweetType:self.tweetType] autorelease];
    self.tableView.dataSource = timelineDataSource;
    self.tableView.delegate   = timelineDataSource;
    
    if (load) [self loadTimeline];
}


- (IBAction) reload:(id) sender
{
    self.navigationItem.leftBarButtonItem.enabled = false;
    [timelineDataSource getTimeline];
}


- (void)autoRefresh
{
    [self reload:nil];
}


#pragma mark - tools methods & post methods

- (void) post
{
	[[GuaziAppDelegate getAppDelegate] post:self];
}


- (void)postViewAnimationDidFinish
{
    if (self.navigationController.topViewController != self) return;
    
    if (tweetType == 0) {
        //
        // Do animation if the controller displays friends timeline or sent direct messages.
        //
        NSArray *indexPaths = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:0 inSection:0], nil];
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];
    }
}


- (void)postTweetDidSucceed:(Status*)status
{
    if (tweetType == 0) {
        [timelineDataSource.timeline insertStatus:status atIndex:0];
    }
}


- (void) removeStatus:(Status*)status
{
    [timelineDataSource.timeline removeStatus:status];
    [self.tableView reloadData];
}


- (void) updateFavorite:(Status*)status
{
    [timelineDataSource.timeline updateFavorite:status];
}


//
// TwitterFonApPDelegate delegate
//
- (void)didLeaveTab:(UINavigationController*)navigationController
{
    navigationController.tabBarItem.badgeValue = nil;
    for (int i = 0; i < [timelineDataSource.timeline countStatuses]; ++i) {
        Status* sts = [timelineDataSource.timeline statusAtIndex:i];
        sts.unread = false;
    }
    unread = 0;
}


- (void)scrollToFirstUnread
{
    BOOL flag = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoScrollToFirstUnread"];
    if (flag == false) return;
    
    if (unread) {
        if (unread < [timelineDataSource.timeline countStatuses]) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:unread inSection:0];
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition: UITableViewScrollPositionBottom animated:true];
        }
    }
}


#pragma mark - TimelineDelegate


- (void)timelineDidUpdate:(FriendsTimelineDataSource*)sender count:(int)count insertAt:(int)position
{
    self.navigationItem.leftBarButtonItem.enabled = true;

	GuaziAppDelegate* appDelegate = [GuaziAppDelegate getAppDelegate];
	NSInteger selectedTab = appDelegate.tabBarController.selectedIndex;
	UINavigationController* nav = [appDelegate.tabBarController.viewControllers objectAtIndex:selectedTab];
    if ( nav.topViewController == self ) {
	//if (self.navigationController.tabBarController.selectedIndex == 1 &&
    //    self.navigationController.topViewController == self) {

        [self.tableView beginUpdates];
        if (position) {
            NSMutableArray *deletion = [[[NSMutableArray alloc] init] autorelease];
            [deletion addObject:[NSIndexPath indexPathForRow:position inSection:0]];
            [self.tableView deleteRowsAtIndexPaths:deletion withRowAnimation:UITableViewRowAnimationBottom];
        }
        if (count != 0) {
            NSMutableArray *insertion = [[[NSMutableArray alloc] init] autorelease];
            
            int numInsert = count;
            // Avoid to create too many table cell.
            //if (numInsert > 8) numInsert = 8;
            for (int i = 0; i < numInsert; ++i) {
                [insertion addObject:[NSIndexPath indexPathForRow:position + i inSection:0]];
            }        
            [self.tableView insertRowsAtIndexPaths:insertion withRowAnimation:UITableViewRowAnimationTop];
        }
        [self.tableView endUpdates];

        if (position == 0 && unread == 0) {
            [self performSelector:@selector(scrollToFirstUnread) withObject:nil afterDelay:0.4];
        }
    }
    if (count) {
        unread += count;
		if ( tweetType == 0 ) {
			[self navigationController].tabBarItem.badgeValue = [NSString stringWithFormat:@"%d", unread];
		}
    }

}


- (void)timelineDidFailToUpdate:(FriendsTimelineDataSource*)sender position:(int)position
{
    self.navigationItem.leftBarButtonItem.enabled = true;
}



#pragma mark - show picture method


- (void) preparedForPicture
{
    UIView* theView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    [theView setBackgroundColor:[UIColor colorWithRed:0.5f green:0.5f blue:0.6f alpha:0.5f]];
    theView.hidden = YES;
    theView.userInteractionEnabled = NO;
    self.grayBackgroundView = theView;
    [self.view addSubview:theView];
    [theView release];
    
    self.middlePicture = [[[UIImageView alloc] initWithFrame:CGRectZero] autorelease];
    self.middlePicture.layer.masksToBounds=YES;
    self.middlePicture.layer.cornerRadius=10.0;
    self.middlePicture.layer.borderWidth=5.0;
    self.middlePicture.layer.borderColor=[[UIColor lightGrayColor] CGColor]; 
    self.middlePicture.frame = CGRectMake(160, 240, 0, 0);
    [self.grayBackgroundView addSubview:self.middlePicture];
}


- (void) showPicture:(UIImage*)image
{
    CGPoint p = self.tableView.contentOffset;
    
    self.grayBackgroundView.frame = CGRectMake(p.x, p.y, 320, 480);
    self.middlePicture.frame = CGRectMake(160, 240, 0, 0);

    CGContextRef context = UIGraphicsGetCurrentContext();
	[UIView beginAnimations:nil context:context];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationDuration:0.5];
    
    self.grayBackgroundView.hidden = NO;
    
    self.middlePicture.image = image;
    self.middlePicture.frame = CGRectMake( 20.0f, 50.0f, 280, 280);
    
	[UIView commitAnimations];
    
    self.grayBackgroundView.userInteractionEnabled = YES;
    self.tableView.scrollEnabled = NO;
}


- (void) hiddenBackgroundView
{
    self.grayBackgroundView.hidden = YES;
    self.tableView.scrollEnabled = YES;
}


@end

